package com.magicborrow.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.security.mobile.module.commonutils.LOG;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.activity.ActivitiesTagsActivity;
import com.magicborrow.activity.BorrowStuffDetailActivity;
import com.magicborrow.activity.CommonViewPagerActivity;
import com.magicborrow.activity.HomepageActivity;
import com.magicborrow.activity.HotWareActivity;
import com.magicborrow.activity.NearWareActivity;
import com.magicborrow.activity.WebImageActivity;
import com.magicborrow.beans.HomeHeadBean;
import com.magicborrow.beans.StringBean;
import com.magicborrow.beans.StuffBean;
import com.magicborrow.enums.PriceModeEnum;
import com.magicborrow.utils.ImageLoadUtil;
import com.magicborrow.utils.StringUtil;
import com.magicborrow.utils.UIHelper;
import com.magicborrow.view.MyHorizontalScrollView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.ArrayList;

/**
 * Created by ghost on 16/3/28.
 */
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_FOOT = 0;
    private static final int TYPE_HEAD = 1;
    private static final int TYPE_NORMAL = 2;
    private ArrayList<StuffBean> data;
    private Context context;
    private LayoutInflater mLayoutInflater;
    private DisplayImageOptions options;
    private HomeHeadBean homeBean;
    private ArrayList<HomeHeadBean.Tags> tags;

    private int initPosition;

    public HomeAdapter(Context pContext) {
        this.context = pContext;
        mLayoutInflater = LayoutInflater.from(context);
    }

    public void setData(ArrayList pData) {
        this.data = pData;
    }

    public ArrayList<StuffBean> getData() {
        return this.data;
    }

    public void setHomeHead(HomeHeadBean bean) {
        this.homeBean = bean;
        this.tags = bean.getTags();
    }

    private int headCount = 1;
    private int footCount = 1;

    private int getItemContentCount() {
        return data.size();
    }

    @Override
    public int getItemViewType(int position) {
        int dataItemCount = getItemContentCount();
        if (headCount != 0 && position < headCount) {
            //头部View
            return TYPE_HEAD;
        } else if (footCount != 0 && position >= (footCount + dataItemCount)) {
            //底部View
            return TYPE_FOOT;
        } else {
            //内容View
            return TYPE_NORMAL;
        }
    }

    @Override
    public int getItemCount() {
        return data.size() + headCount + footCount;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_FOOT) {
            View view = mLayoutInflater.inflate(R.layout.load_more_footer, null);
            view.setTag("foot");
            return new FootViewHolder(view);
        } else if (viewType == TYPE_NORMAL) {
            View view = mLayoutInflater.inflate(R.layout.home_item, null);
            return new HomeItemViewHolder(view);
        } else if (viewType == TYPE_HEAD) {
            View view = mLayoutInflater.inflate(R.layout.home_item_head, null);
            return new HeadViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof HomeItemViewHolder) {
            HomeItemViewHolder hold = (HomeItemViewHolder) holder;
            final StuffBean bean = data.get(position - 1);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, BorrowStuffDetailActivity.class);
                    intent.putExtra("data", bean);
                    context.startActivity(intent);
                }
            });
            hold.tvName.setText(bean.getUser().getNickname());
            hold.rbPingfen.setRating(bean.getUser().getLendScaleAVG());
            hold.tvPingFen.setText("" + StringUtil.double2String(bean.getUser().getLendScaleAVG()) + "（" + bean.getCommentCount() + "人评价）");


            if (options == null)
                options = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(context.getResources().getDimensionPixelOffset(R.dimen._30dp))).build();

            //      http://123.56.253.139/data/mojie//ava/11/0/0/80.jpg?t=1463498007000
            ImageLoader.getInstance().displayImage(Constants.ADDRESS + bean.getUser().getAvatar80(),
                    hold.imvHead, options);
            hold.llImg.removeAllViews();
            final ArrayList<String> imgUrls = new ArrayList<>();
            for (StuffBean.ImagesEntity img : bean.getImages()) {
                imgUrls.add(img.getOrigin());

            }
            for (int i = 0; i < imgUrls.size(); i++) {
                ImageView imv = createImageView(bean.getImages().get(i));
                final int finalI = i;
                imv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                   /*     position = getIntent().getIntExtra("position", 0);
                        imageUrlList = getIntent().getStringArrayListExtra("netImageUrls");*/
                        Intent intent = new Intent(context, CommonViewPagerActivity.class);
                        intent.putExtra("position", finalI);
                        intent.putExtra("netImageUrls", imgUrls);
                        context.startActivity(intent);

                    }
                });
                ((HomeItemViewHolder) holder).llImg.addView(imv);
            }
            hold.tvAddress.setText(bean.getAddress());
            hold.stuffName.setText(bean.getName());
            hold.tvPrice.setText("￥" + bean.getPrice() + "/" + PriceModeEnum.getModeStr(bean.getPriceMode()));
            hold.tvInfo.setText(bean.getDescription());
            hold.llTag.removeAllViews();
            for (int i = 0; i < bean.getTags().size(); i++) {
                ((HomeItemViewHolder) holder).llTag.addView(createTag(bean.getTags().get(i).getName()));
            }
            //进入到他的主页
            ((HomeItemViewHolder) holder).imvHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, HomepageActivity.class);
                    intent.putExtra("id", data.get(position - 1).getUser().getId());
                    context.startActivity(intent);
                }
            });
        } else if (holder instanceof HeadViewHolder) {
            final HeadViewHolder hol = (HeadViewHolder) holder;
            if (homeBean == null) {
                return;
            }

            ((HeadViewHolder) holder).carouselPoints.removeAllViews();
            for (int i = 0; i < homeBean.getSliedes().size(); i++) {
                View view = new View(context);
                view.setBackgroundResource(R.drawable.all_point);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
                if (i != 0) {
                    params.leftMargin = 15;
                }
                view.setEnabled(false);
                view.setLayoutParams(params);
                ((HeadViewHolder) holder).carouselPoints.addView(view);
            }
            initPosition = 0;
            ((HeadViewHolder) holder).carouselPoints.getChildAt(initPosition).setEnabled(true);
            ((HeadViewHolder) holder).mHeadViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    ((HeadViewHolder) holder).carouselPoints.getChildAt(initPosition).setEnabled(false);
                    ((HeadViewHolder) holder).carouselPoints.getChildAt(position).setEnabled(true);
                    initPosition = position;
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });


            ImageViewPagerAdapter adapter = new ImageViewPagerAdapter(context, homeBean.getSliedes());
            hol.mHeadViewPager.setAdapter(adapter);


            LinearLayout one;
            LinearLayout.LayoutParams params;
            ImageView imageView;
            TextView textView;
            //  int width = UIHelper.dip2px(context, 50);
            int width = (int) (UIHelper.getScreenWidth(context) * 9.0 / 75);
            hol.linearLayout.removeAllViews();
            for (int i = 0; i < tags.size(); i++) {
                final HomeHeadBean.Tags tag = tags.get(i);
                one = new LinearLayout(context);
                params = new LinearLayout.LayoutParams((int) (UIHelper.getScreenWidth(context) * 145.0 / 750), LinearLayout.LayoutParams.WRAP_CONTENT);
                //params.leftMargin = UIHelper.dip2px(context, 14);
                one.setLayoutParams(params);
                one.setOrientation(LinearLayout.VERTICAL);
                one.setBackgroundResource(R.drawable.down_selector);

                imageView = new ImageView(context);
                params = new LinearLayout.LayoutParams(width, width);
                params.gravity = Gravity.CENTER_HORIZONTAL;
                imageView.setLayoutParams(params);
                ImageLoadUtil.loadImage(imageView, Constants.ADDRESS + tags.get(i).getIcon(), R.mipmap.empty_photo);

                textView = new TextView(context);
                params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                params.gravity = Gravity.CENTER_HORIZONTAL;
                params.topMargin = UIHelper.dip2px(context, 5);
                textView.setLayoutParams(params);
                textView.setText(tags.get(i).getName());

                one.addView(imageView);
                one.addView(textView);
                one.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra("tagId", tag.getId());
                        intent.putExtra("name", tag.getName());
                        intent.setClass(context, ActivitiesTagsActivity.class);
                        context.startActivity(intent);
                    }
                });
                hol.linearLayout.addView(one);
            }

            hol.more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
//                    intent.setClass(context, HotWareActivity.class);
                    intent.setClass(context, NearWareActivity.class);// 跳转到附近
                    context.startActivity(intent);
                }
            });
            hol.mHeadViewPager.setCurrentItem(0);
        }
    }

    private TextView createTag(String tag) {
        TextView tv = new TextView(context);
        tv.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.tag_bg));
        tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimensionPixelSize(R.dimen.text_size_small_s));
        tv.setTextColor(context.getResources().getColor(R.color.orange_red));
        tv.setText("" + tag);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, context.getResources().getDimensionPixelOffset(R.dimen._5dp), 0);
        tv.setLayoutParams(params);
        return tv;
    }

    @NonNull
    private ImageView createImageView(StuffBean.ImagesEntity imagesEntity) {
        final ImageView imv = new ImageView(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.setMargins(context.getResources().getDimensionPixelOffset(R.dimen.layout_padding_nor), 0, 0, 0);
        imv.setScaleType(ImageView.ScaleType.FIT_XY);
        params.width = imagesEntity.getWidth() * context.getResources().getDimensionPixelOffset(R.dimen._150dp) / imagesEntity.getHeight();
        imv.setLayoutParams(params);
        ImageLoader.getInstance().displayImage(Constants.ADDRESS + imagesEntity.getPreview(), imv);
        return imv;
    }

    public class HomeItemViewHolder extends RecyclerView.ViewHolder {
        private TextView tvAddress;
        private TextView tvPrice;
        private TextView tvPingFen;
        private ImageView imvHead;
        private TextView tvName;
        private RatingBar rbPingfen;
        private LinearLayout llImg;
        private TextView stuffName;
        private TextView tvInfo;
        private LinearLayout llTag;

        public HomeItemViewHolder(View view) {
            super(view);
            imvHead = (ImageView) view.findViewById(R.id.imv_head);
            tvName = (TextView) view.findViewById(R.id.tv_name);
            tvAddress = (TextView) view.findViewById(R.id.tv_address);
            tvPingFen = (TextView) view.findViewById(R.id.tv_pingfen);
            tvPrice = (TextView) view.findViewById(R.id.tv_price);
            tvInfo = (TextView) view.findViewById(R.id.tv_info);
            rbPingfen = (RatingBar) view.findViewById(R.id.rb_pingfen);
            llImg = (LinearLayout) view.findViewById(R.id.ll_img);
            stuffName = (TextView) view.findViewById(R.id.stuff_name);
            llTag = (LinearLayout) view.findViewById(R.id.ll_tag);
        }
    }

    public class FootViewHolder extends RecyclerView.ViewHolder {

        public FootViewHolder(View itemView) {
            super(itemView);
        }

    }

    public class HeadViewHolder extends RecyclerView.ViewHolder {

        private ViewPager mHeadViewPager;
        private LinearLayout linearLayout;
        private View more;
        private LinearLayout carouselPoints;
        private LinearLayout llDot;
        private ImageView imvDot;

        public HeadViewHolder(View itemView) {
            super(itemView);
            imvDot = (ImageView) itemView.findViewById(R.id.imv_dot);
            llDot = (LinearLayout) itemView.findViewById(R.id.ll_dot);
            carouselPoints = (LinearLayout) itemView.findViewById(R.id.carousel_point);

            mHeadViewPager = (ViewPager) itemView.findViewById(R.id.viewPager);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIHelper.getScreenWidth(context) * 6 / 15);

            mHeadViewPager.setLayoutParams(layoutParams);
            linearLayout = (LinearLayout) itemView.findViewById(R.id.ll_img);
            ViewGroup.LayoutParams params = linearLayout.getLayoutParams();
            int left = (UIHelper.getScreenWidth(context) - 5 * (int) (UIHelper.getScreenWidth(context) * 145.0 / 750.0)) / 2;
            linearLayout.setPadding(left, left, left, left);
            params.height = UIHelper.getScreenWidth(context) * 192 / 750;
            linearLayout.setLayoutParams(params);
            linearLayout.setGravity(Gravity.CENTER_VERTICAL);
            more = (View) itemView.findViewById(R.id.more);

            final MyHorizontalScrollView scrollView = (MyHorizontalScrollView) linearLayout.getParent();
            scrollView.setOnScrollChangeListener(new MyHorizontalScrollView.OnScrollChangeListener() {
                @Override
                public void scrollChange(int l, int t, int oldl, int oldt) {
                    double b = ((double) l) / (scrollView.getWidth());
                    imvDot.setX((int) ((llDot.getWidth() / 2+context.getResources().getDimensionPixelOffset(R.dimen._6dp) )* b));
                  //  imvDot.setRight(imvDot.getWidth()+(int) (llDot.getWidth() / 2 * b));

                }
            });
        }

    }


    private class ImageViewPagerAdapter extends PagerAdapter {

        private Context context;
        private ArrayList<HomeHeadBean.Slides> urls;

        public ImageViewPagerAdapter(Context pContext, ArrayList<HomeHeadBean.Slides> pUrls) {
            this.context = pContext;
            this.urls = pUrls;
        }

        @Override
        public int getCount() {
            return urls.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            if (view != null) {
                // view.removeViewAt(position);
            }
        }

        @Override
        public Object instantiateItem(ViewGroup view, final int position) {
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ImageLoadUtil.loadImage(imageView, Constants.ADDRESS + urls.get(position).getThumbnail(), R.mipmap.empty_photo);
            view.addView(imageView);

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, WebImageActivity.class);
                    intent.putExtra("urls", urls.get(position).getUrl());
                    context.startActivity(intent);
                }
            });


            return imageView;
        }

    }

}
